import { config } from './modules/config';
var resources = require('./modules/services/resources-service');
var uploads = require('./modules/services/uploads-service');
var lingo = require('lingo');
var lodash = require('lodash');

export function doResourcesPut(req, res, next, noEvent?) {
    var promise = null;
    if (req.headers['mpj-sync-single-package']) {
        var children = req.body.children;
        delete req.body.children;
        var syncInfo = {
            excludedBindId: req.headers['mpj-sync-terminal-bind-id'],
            lastSyncTime: req.headers['mpj-sync-last-sync-time']
        };
        promise = resources.lockReturnFull(children.map(function (child) {
            return { id: child.obj.id, version: lodash.get(child.obj, 'extended.version.version') };
        }), req.body.terminalId, req.body.userName, syncInfo).then(function (versions) {
            return Promise.all(children.map(function (child, index) {
                resources.initExtended(child.obj);
                child.obj.extended.version = lodash.omit(versions.versions[index], 'stale');
                var _type = lodash.result(config.type2spUrl, child.type);
                return doResourceSave({
                    params: {
                        storeId: req.params.storeId,
                        resEntity: _type || child.type,
                        resId: child.obj.id
                    },
                    headers: {
                        'mpj-sync-time-expire': child.timeExpire,
                        'mpj-sync-resource-version': child.resourceVersion,
                        'mpj-sync-packed': req.body.id,
                        'mpj-sync-terminal-bind-id': req.headers['mpj-sync-terminal-bind-id']
                    },
                    body: child.obj
                }, noEvent);
            })).then(function () {
                req.body.resources = lodash.map(children, function (child) {
                    return { id: child.obj.id, uri: child.uri, type: child.type };
                });
                return doResourceSave(req, noEvent);
            })
        });
    } else {
        promise = doResourceSave(req, noEvent);
    }
    return promise.then(function () {
        console.log("doResourcesPut success!");
    }).catch(function (err) {
        console.log("doResourcesPut error:", err);
    });
}

export function doResourceSave(req, noEvent?) {
    var promise = null;
    if (req.headers['mpj-sync-resource-version']) {
        promise = resources.isOutOfVersion(req.params.resId, parseInt(req.headers['mpj-sync-resource-version']));
    } else {
        promise = Promise.resolve(false);
    }
    return promise.then(function (isExpired) {
        if (isExpired)
            return;
        return uploads.saveUploads(getSyncURIFromPUTReq(req), req.params, req.headers, req.body).then(function () {
            if (req.params.resEntity != 'workshifts') {
                return resources.putUpdate(newResourceFromPUTReq(req), getIsNoSendNotificationFromPUTReq(req), noEvent);
            }
        });
    });
}


export function getSyncURIFromPUTReq(req, other?) {
    var url = '/api/stores/' + req.params.storeId + '/' + req.params.resEntity + '/' + req.params.resId;
    lodash.forEach(other, function (item) {
        url += item;
    });
    return url;
}

function newResourceFromPUTReq(req) {
    var resId = req.params.resId;
    var resource: any = {
        updateId: resId,
        id: resId,
        state: getSyncStateFromPUTReq(req),
        uri: getSyncURIFromPUTReq(req),
        data: req.body,
        timeWhen: new Date().getTime()
    };

    // 先从配置中查找是否有特殊的
    var resEntity = req.params.resEntity;
    var type = lodash.result(config.spUrl2Type, resEntity);
    if (type) {
        resource.type = type;
    } else {
        resource.type = lingo.en.singularize(resEntity);
    }

    if (req.headers['mpj-sync-time-expire']) {
        resource.timeExpire = parseInt(req.headers['mpj-sync-time-expire']);
    }
    if (req.headers['mpj-sync-resource-version']) {
        resource.version = parseInt(req.headers['mpj-sync-resource-version']);
    }
    if (req.headers['mpj-sync-terminal-bind-id']) {
        resource.terminalBindId = req.headers['mpj-sync-terminal-bind-id']
    }
    return resource;
}

function getIsNoSendNotificationFromPUTReq(req) {
    return req.headers['mpj-sync-packed'] && req.params.resEntity != 'sync-packages'
}

function getSyncStateFromPUTReq(req) {
    return req.params.hasOwnProperty('state') ? req.params.state : 0;
}

